package msg

import (
	"context"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	uuid "github.com/satori/go.uuid"
	"go-zero-project/services/user/api/constans"
	"go-zero-project/services/user/api/internal/svc"
	"go-zero-project/services/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DefaultMsgLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDefaultMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DefaultMsgLogic {
	return &DefaultMsgLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DefaultMsgLogic) DefaultMsg(req *types.SendDefaultMsgReq) (resp *types.SendDefaultMsgResp, err error) {
	// covert request
	bodyByte := []byte(req.Msg)
	message := primitive.Message{Topic: constans.UserDefaultTopic, Body: bodyByte}
	message.WithTag("default")
	message.WithKeys([]string{uuid.NewV4().String()})
	// send msg
	sendResult, err := l.svcCtx.DefaultProducer.SendSync(l.ctx, &message)
	if err != nil {
		return nil, err
	}
	logx.Infof("msgId %s,topic:%s,send msg:%s!",
		sendResult.MsgID, message.Topic, string(message.Body))
	// return obj
	return &types.SendDefaultMsgResp{Topic: constans.UserDefaultTopic,
		Msg: string(bodyByte), Tag: "default"}, nil

}
